<?php
class Pageley_Domain_LazyReferenceProperty implements Pageley_Domain_Property {

	private $idValue;
    private $entityValue;
	private $type;
	private $valueProvider;
	private $initialized;

	public function __construct($idValue, $type) {
		$this->idValue = $idValue;
		$this->type = $type;
		$this->initialized = false;
	}
    
	public function getValue($load = true) {
		if(!$this->initialized && $load) {
            $this->initialized = true;
            $type = $this->type;
            $id = $this->idValue;
		    if($this->idValue === null || $this->valueProvider === null) {
                $value = null;
            } else {
				$value = $this->valueProvider->find($type, $id);
	            if($value === null) {
	                throw new Pageley_Domain_RuntimeException("Reference attribute with type '" . $type . "' contained invalid ID (" . $id . ").");
	            }
            }
            $this->entityValue = $value;
		}
		return $this->entityValue;
	}

	public function isInitialized() {
		return $this->initialized;
	}

    public function setValue($value) {
    	if(is_numeric($value)) {
    		$this->idValue = $value;
    	} else {
            $this->entityValue = $value;
            $this->initialized = true;
    	}
    }

    public function setValueProvider($valueProvider) {
        $this->valueProvider = $valueProvider;
    }

    public function __toString() {
		return $this->initialized ? "" . $this->entityValue : "" . $this->idValue;
	}

	public function equals($object) {
		if($object === null) {
			return false;
		}
		if(!($object instanceof Pageley_Domain_LazyReferenceProperty)) {
			return false;
		}
		return initialized ? Pageley_Util_Equals::isEqual($this->entityValue, $object->entityValue)
            : Pageley_Util_Equals::isEqual($this->idValue, $object->idValue) &&
                Pageley_Util_Equals::isEqual($this->type, $object->type);
	}
}